<?php

namespace App\Supports\Payment\Methods\Adawxmini;

use Exception;
use Brick\Math\RoundingMode;
use App\Supports\Payment\Methods\Method;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use App\Supports\Payment\Contracts\MethodRefund;

class RefundOrder extends Method implements MethodRefund
{
	public function validate($refund = null, $data = null)
	{
		if (! $refund->order->isPaid()) {
			abort(403, '目标订单未支付');
		}
		if ($refund->order->isClosed()) {
			abort(403, '目标订单已关闭');
		}
		if ($refund->order->isCancelled()) {
			abort(403, '目标订单已取消');
		}
		if ($refund->order->has_refund) {
			abort(403, '目标订单已退款');
		}
		if ($refund->order->paid_method !== 'adawxmini') {
			abort(403, '目标订单不能通过汇付退款');
		}
		if ($refund->refund_status !== 'confirmed') {
			abort(403, '目标售后未审核');
		}
	}

	public function info($refund = null)
	{
		$paymentId = $refund->order->paid_number;
		$refundOrderNo = $refund->refund_number;
		$refundAmt = big_decimal($refund->refund_money)->toScale(2, RoundingMode::HALF_UP);
        $notifyUrl = route('web.payments.adapay.refund.notify');

		$refund->update(['refund_status' => 'processing']);

		return [
			'payment_id' => $paymentId,
			'refund_order_no' => $refundOrderNo,
			'refund_amt' => $refundAmt,
			'notify_url' => $notifyUrl,
		];
	}

	public function refund($refund = null)
	{
		$this->validate($refund);

		try {
			$info = $this->info($refund);
			$refund = $this->channel->refund($info);

			if ($refund->isError()) {
				abort(400, $refund->result['error_msg']);
			}
		} catch (Exception $exception) {
			Log::debug($exception->getCode());
			Log::debug($exception->getMessage());
			throw ValidationException::withMessages(['err' => '支付暂不可用!']);
		}
	}
}
